﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using Hangjing.Common;
using Hangjing.SQLServerDAL;
using Hangjing.Model;
using Hangjing.DBUtility;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;

/// <summary>
/// 订单调度系统
/// </summary>
public partial class qy_54tss_Admin_GpsSet_OrderDelive : System.Web.UI.Page
{

    Deliver daldel = new Deliver();
    private string SqlWhere
    {
        get
        {
            object o = ViewState["SqlWhere"];
            return (o == null) ? "" : Convert.ToString(o);
        }
        set
        {
            ViewState["SqlWhere"] = value;
        }
    }


    protected string ordersort
    {
        get
        {
            object o = ViewState["ordersort"];
            return (o == null) ? "orderTime" : Convert.ToString(o);
        }
        set
        {
            ViewState["ordersort"] = value;
        }
    }

    /// <summary>
    /// 城市编号
    /// </summary>
    protected int cityid
    {
        get
        {
            object o = ViewState["cityid"];
            return (o == null) ? 0 : Convert.ToInt32(o);
        }
        set
        {
            ViewState["cityid"] = value;
        }
    }

    Custorder dal = new Custorder();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            EAdminInfo admin = UserHelp.GetAdmin();
            if (admin == null)
            {
                Response.Redirect("../login.aspx");
                return;
            }
            WebUtility.checkOperator(1);
            ordersort = "SendTime asc,orderdatetime ";


            hidLat.Value = SectionProxyData.GetSetValue(4);
            hidLng.Value = SectionProxyData.GetSetValue(5);
            string cityname = "";




            cityid = HjNetHelper.GetQueryInt("cid", 0);
            if (cityid == 0)
            {

                if (admin.CityID > 0)
                {
                    //CityInfo city = new City().GetModel(admin.CityID);
                    CityInfo city = CacheHelper.GetCityList().Where(a => a.cid == admin.CityID).FirstOrDefault();
                    if (city != null)
                    {
                        hidLat.Value = city.Lat;
                        hidLng.Value = city.Lng;
                        cityname = city.cname;
                        cityid = city.cid;
                    }
                }
                else
                {
                    string cityid_cookie = WebUtility.FixgetCookie("d_cityid");
                    if (cityid_cookie == null || cityid_cookie == "")
                    {
                        hfflag.Value = "1";
                        return;
                    }
                    else
                    {
                        cityid = Convert.ToInt32(cityid_cookie);
                        cityname = Server.UrlDecode(WebUtility.FixgetCookie("d_cityname"));
                    }
                }
            }
            else
            {
                CityInfo city = CacheHelper.GetCityList().Where(a => a.cid == cityid).FirstOrDefault();
                if (city != null)
                {
                    hidLat.Value = city.Lat;
                    hidLng.Value = city.Lng;
                    cityname = city.cname;
                    cityid = city.cid;
                }

            }

            WebUtility.FixsetCookie("d_cityid", cityid.ToString(), 30);
            WebUtility.FixsetCookie("d_cityname", Server.UrlEncode(cityname), 30);


            hfcityname.Value = cityname;
            hfcityid.Value = cityid.ToString();


            SqlWhere = "  ReveVar1 = '0' and Custorder.delflag = 0 and OrderDateTime > '" + DateTime.Now.AddDays(-1).ToString() + "'  ";
            if (HjNetHelper.GetQueryString("oid") != "")
            {
                string oid = HjNetHelper.GetQueryString("oid");
                SqlWhere += " and ( Custorder.OrderID like '%" + oid + "%')";
            }
            SqlWhere += " and Custorder.cityid = " + cityid;



            int scope = HjNetHelper.GetQueryInt("scope", -1);
            if (scope > -1)
            {
                WebUtility.FixsetCookie("admin_scope", scope + "", 30);
            }
            else
            {
                string scopecookie = WebUtility.FixgetCookie("admin_scope");
                if (scopecookie != null && scopecookie != "")
                {
                    scope = Convert.ToInt32(scopecookie);
                }
            }

            if (scope > 0 && scope != Constant.allOrderTag)
            {
                SqlWhere = new RightsTool().getOrderWhere(SqlWhere, scope);
            }

            lbsendtimelabel.InnerText = "配送计时";
            switch (HjNetHelper.GetQueryInt("type", 0))
            {
                case 0:
                    SqlWhere += " and OrderStatus  <= 2 "; //未调度
                    break;
                case 10:
                    SqlWhere += " and OrderStatus=7 and sendstate=0  "; //未接收
                    lbsendtimelabel.InnerText = "调度计时";
                    break;
                case 1:
                    SqlWhere += " and OrderStatus = 7 "; //未完成

                    ordersort = "OrderStatus desc, DispatchTime desc,  SendTime ";

                    break;
                case 2:
                    break;
            }


            //获取订单列表 需要做分页
            BindOrderData();
            this.snDate.InnerHtml = cityname + "[<a href=\"javascript:show_citytable();\" class='orange'>切换城市</a>]";

            IList<DeliverGroupInfo> groups = SectionProxyData.GetEdelivergroupList().Where(a => a.Status == cityid).ToList();

            WebUtility.BindList("id", "classname", groups, ddlgroup);



            if (admin.AdminStatus > 0)
            {
                WebUtility.BindRepeater(rptmygroup, groups.Where(a=>a.ID == admin.AdminStatus).ToList());
            }
            else
            {
                WebUtility.BindRepeater(rptmygroup, groups);
            }



            new OrderState().BindOrderState(ddlstate);

        }

    }

    private void BindOrderData()
    {
        if (SqlWhere == null || SqlWhere.Length == 0)
        {
            return;
        }

        AspNetPager1.RecordCount = dal.GetCount(SqlWhere);
        IList<CustorderInfo> xist = dal.GetListForDelive(AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex, SqlWhere, ordersort, 0);
        int type = HjNetHelper.GetQueryInt("type", 0);
        foreach (var item in xist)
        {
            if (type == 10)
            {
                item.DeliveInfo.OverTimeStr = item.DeliveInfo.dispatchTimeStr;
            }
            if (item.TogoId == 0)
            {
                item.TogoName = item.OrderAddress + "（" + item.OrderAddrEx + "）";
            }
        }
        this.rptOrderList.DataSource = xist;
        rptOrderList.DataBind();
        this.AspNetPager1.RecordCount = dal.GetCount(SqlWhere);
    }



    protected void AspNetPager1_PageChanged(object sender, EventArgs e)
    {
        BindOrderData();
    }



    /// <summary>
    /// 确认开始分配配送员
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void deliver_click(object sender, EventArgs e)
    {
        int did = Convert.ToInt32(hfdid_hh.Value);
        DeliverInfo model = daldel.GetModel(did);
        if (model != null)
        {
            OrderDeliver dalod = new OrderDeliver();

            string oid = WebUtility.InputText(hforderid.Value);

            OrderDeliverInfo odmodel = dalod.GetModel(oid);
            if (odmodel == null)
            {
                odmodel = new OrderDeliverInfo();
            }
            odmodel.Orderid = oid;
            odmodel.DeliverId = did;
            odmodel.DeliverName = model.Name;
            odmodel.Dispatcher = UserHelp.GetAdmin().AdminName;
            odmodel.DispatchTime = DateTime.Now;
            odmodel.DeliveryTime = DateTime.Now;
            odmodel.Inve1 = 0;
            odmodel.Inve2 = "";
            odmodel.Section = "0";

            int id = 0;
            if (odmodel.DataId > 0)
            {
                id = dalod.Update(odmodel);
            }
            else
            {
                id = dalod.Add(odmodel);
            }

            if (id > 0)
            {

                CustorderInfo order = dal.GetModel(oid);
                if (order.deliverid > 0 && order.deliverid != odmodel.DeliverId)//换人了
                {
                    daldel.InitWorkState(order.deliverid);
                }

                //记录
                dal.AddOrderRecord(odmodel.Orderid, 7, UserHelp.GetAdmin().AdminName, "管理员修改订单信息:调度页面（调度）");
                {
                    NoticeHelper notice = new NoticeHelper(Context, did.ToString(), hforderid.Value.Trim());
                    notice.sendOrderToDeliver();

                }

                //给商家消息
                {
                    NoticeHelper notice = new NoticeHelper(Context);
                    notice.sendNotice2Shop(order.TogoId, "订单" + oid + "已经分配配送员", oid);
                }

                AlertScript.RegScript(Page, UpdatePanel1, "alert('操作成功,订单已经调度');pageinit(); $('#tr" + oid + "').remove();");



            }
            else
            {
                AlertScript.RegScript(Page, UpdatePanel1, "alert('操作失败');pageinit();");
            }
            hfdid_hh.Value = "0";
        }
        else
        {
            //
        }
        //OrderDeliver 添加记录
    }


    /// <summary>
    /// 订单分配给群组
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void sendgroup_click(object sender, EventArgs e)
    {

        string oid = WebUtility.InputText(hforderid.Value).Trim();
        int gid = Convert.ToInt32(ddlgroup.SelectedValue);
        //记录
        dal.AddOrderRecord(oid, 7, UserHelp.GetAdmin().AdminName, "管理员修改订单信息:调度页面（发群）");


        autodispatchconfigInfo config = CacheHelper.Getautodispatchconfig().Where(a => a.reveint2 == gid).FirstOrDefault();
        if (config != null && config.isopen == 1)
        {

            CustorderInfo order = dal.GetModel(oid);
            IList<ROrderinfo> olist = new List<ROrderinfo>();

            ROrderinfo m = new ROrderinfo();

            m.cardpay = 0;
            m.latlng = order.ReveVar2;
            m.sentorg = "0";
            m.cityid = order.cityid;
            m.groupid = gid;
            m.Orderid = oid;
            olist.Add(m);

            dal.AutoDispatch(olist);
        }
        else
        {
            //订单表中也保存配送员编号，便于统计,修改订单状态:
            string sql = "update Custorder set deliverheaderid=" + gid + ",OrderStatus=7,deliverid=0,sendstate=0  where OrderID='" + hforderid.Value.Trim() + "'";
            WebUtility.excutesql(sql);
            NoticeHelper notice = new NoticeHelper(Context, gid.ToString());
            notice.send2Group();
        }

        BindOrderData();
        hfdid_hh.Value = "0";
        tborderinfo.Value = "";


        AlertScript.RegScript(Page, UpdatePanel1, "alert('操作成功,订单已经调度');pageinit();");
    }



    /// <summary>
    /// 搜索
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void search_click(object sender, EventArgs e)
    {
        SqlWhere = " ReveVar1 = '0' and Custorder.delflag = 0 ";
        SqlWhere = new RightsTool().getOrderWhere(SqlWhere, false);
        string key = WebUtility.InputText(tbkeyword.Value);
        if (key != "" && key != "可按照电话、姓名、订单号查询")
        {
            SqlWhere += " and (OrderComm like '%" + key + "%' or OrderRcver like '%" + key + "%' or Custorder.OrderID like '%" + key + "%')";
        }
        if (ddlstate.SelectedValue != "0")
        {
            SqlWhere += " and OrderStatus = " + ddlstate.SelectedValue + "";
        }
        if (tbdelivername.Value != "")
        {
            SqlWhere = SqlWhere + " and EXISTS (SELECT * FROM dbo.Deliver WHERE DataId = dbo.Custorder.deliverid AND Name LIKE '%" + WebUtility.InputText(tbdelivername.Value) + "%')";
        }

        if (tbAddressText.Value.Trim() != "")
        {
            SqlWhere += " and AddressText like '%" + WebUtility.InputText(tbAddressText.Value) + "%'";

        }
        if (tbOrderAttach.Value.Trim() != "")
        {
            SqlWhere += " and OrderAttach like '%" + WebUtility.InputText(tbOrderAttach.Value) + "%'";

        }



        SqlWhere += " and Custorder.cityid = " + cityid;
        BindOrderData();
    }

    /// <summary>
    /// 时间差
    /// </summary>
    /// <param name="time1"></param>
    /// <param name="time2"></param>
    /// <returns></returns>
    public string getdiffdate(object time1, object time2)
    {
        DateTime t1 = Convert.ToDateTime(time1);
        DateTime t2 = Convert.ToDateTime(time2);

        if (t1 < Convert.ToDateTime("2012-01-01") || t2 < Convert.ToDateTime("2012-01-01"))
        {
            return "";
        }

        TimeSpan ts1 = new TimeSpan(t1.Ticks);
        TimeSpan ts2 = new TimeSpan(t2.Ticks);
        TimeSpan ts = ts1.Subtract(ts2).Duration();
        double minu = Math.Abs(ts.TotalMinutes);
        return minu.ToString("0.0");
    }

    /// <summary>
    /// timeer event
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Timer1_Tick(object sender, EventArgs e)
    {
        string sql = " ReveVar1 = '0'  and OrderStatus in (2)";
        sql += " and Custorder.cityid = " + cityid;
        int count = dal.GetCount(sql);
        if (count != 0)
        {
            AlertScript.RegScript(this.Page, UpdatePanel1, "play(" + count + ");");
        }
        else
        {
            AlertScript.RegScript(this.Page, UpdatePanel1, "play(0);");
        }
        BindOrderData();
    }

    protected void clearGPSReclord_Click(object sender, EventArgs e)
    {
        string sql = "TRUNCATE TABLE dbo.GPS_Records";

        WebUtility.excutesql(sql);
        AlertScript.RegScript(this.Page, this.UpdatePanel1, "alert('删除成功','error','true',5);init();");
    }

    protected void delGPSReclord_Click(object sender, EventArgs e)
    {
        Button lb = (Button)sender;
        int day = Convert.ToInt32(lb.CommandArgument.ToString());

        string sql = "DELETE FROM dbo.GPS_Records WHERE AddTime < '" + DateTime.Now.AddDays(-day) + "'";

        WebUtility.excutesql(sql);
        AlertScript.RegScript(this.Page, this.UpdatePanel1, "alert('删除成功','error','true',5);");
    }

    /// <summary>
    /// 排序
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void sort_click(object sender, EventArgs e)
    {
        LinkButton lb = (LinkButton)sender;
        string currentsort = lb.CommandArgument.ToString();

        if (currentsort == ordersort) //一样的话要排序反一下。
        {
            ordersort = lb.CommandName;
        }
        else
        {
            ordersort = currentsort;
        }

        // Hangjing.AppLog.AppLog.Info("ordersort="+ ordersort);

        BindOrderData();
    }

    //protected override object LoadPageStateFromPersistenceMedium()
    //{
    //    string viewState = Request.Form["__VSTATE"];
    //    if (viewState == null || viewState.Length == 0 )
    //    {
    //        return string.Empty;
    //    }
    //    byte[] bytes = Convert.FromBase64String(viewState);
    //    bytes = Decompress(bytes);
    //    LosFormatter formatter = new LosFormatter();
    //    return formatter.Deserialize(Convert.ToBase64String(bytes));

    //}

    //protected override void SavePageStateToPersistenceMedium(object viewState)
    //{
    //    LosFormatter formatter = new LosFormatter();
    //    using (StringWriter writer = new StringWriter())
    //    {
    //        formatter.Serialize(writer, viewState);
    //        string viewStateString = writer.ToString();
    //        byte[] bytes = Convert.FromBase64String(viewStateString);
    //        bytes = Compress(bytes);
    //        ClientScript.RegisterHiddenField("__VSTATE", Convert.ToBase64String(bytes));
    //    }
    //}




    private ObjectStateFormatter _formatter =
        new ObjectStateFormatter();

    protected override void SavePageStateToPersistenceMedium(object viewState)
    {
        MemoryStream ms = new MemoryStream();
        _formatter.Serialize(ms, viewState);
        byte[] viewStateArray = ms.ToArray();
        ClientScript.RegisterHiddenField("__COMPRESSEDVIEWSTATE",
            Convert.ToBase64String(
            Compress(viewStateArray)));
    }
    protected override object LoadPageStateFromPersistenceMedium()
    {
        string vsString = Request.Form["__COMPRESSEDVIEWSTATE"];
        if (vsString == null)
        {
            return null;
        }
        byte[] bytes = Convert.FromBase64String(vsString);
        bytes = Decompress(bytes);
        return _formatter.Deserialize(
            Convert.ToBase64String(bytes));
    }







    public byte[] Compress(byte[] data)
    {
        MemoryStream output = new MemoryStream();
        using (GZipStream gzip = new GZipStream(output, CompressionMode.Compress, true))
        {
            gzip.Write(data, 0, data.Length);
            gzip.Close();
        }

        return output.ToArray();
    }

    public byte[] Decompress(byte[] data)
    {
        MemoryStream output = new MemoryStream();
        using (MemoryStream input = new MemoryStream())
        {
            input.Write(data, 0, data.Length);
            input.Position = 0;
            GZipStream gzip = new GZipStream(input,
                              CompressionMode.Decompress, true);

            byte[] buff = new byte[64];
            int read = -1;
            read = gzip.Read(buff, 0, buff.Length);
            while (read > 0)
            {
                output.Write(buff, 0, read);
                read = gzip.Read(buff, 0, buff.Length);
            }
            gzip.Close();
        }

        return output.ToArray();
    }

}
